//
//  HYReceivedFlowLayout.m
//  HaiYue
//
//  Created by skyline on 2018/1/12.
//  Copyright © 2018年 skyline. All rights reserved.
//

#import "HYReceivedFlowLayout.h"
@interface HYReceivedFlowLayout ()
@property (nonatomic, strong) NSMutableArray *attributesArray;
@end
@implementation HYReceivedFlowLayout
- (void)prepareLayout
{
    [super prepareLayout];
    self.attributesArray = [NSMutableArray array];
    for (int index = 0; index < [self.collectionView numberOfItemsInSection:0]; index++) {
        UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
        [_attributesArray addObject:attributes];
    }
    self.scrollDirection = UICollectionViewScrollDirectionVertical;
}

/*如果返回yes，collectionview的显示范围发生改变的时候，就会重新刷新布局一旦重新刷新布局，就会按顺序调用下面的方法： prepareLayout layoutAttributesForElementsInRect: */
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}
/*
 说明：1.这个方法的返回值是个数组
      2. 这个数组中存放的都是UICollectionViewLayoutAttributes对象
      3.UICollectionViewLayoutAttributes对象决定了cell的排布方式（frame等）
 */
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return _attributesArray;
}

-(CGSize)collectionViewContentSize
{
    UICollectionViewLayoutAttributes *lastAttr = [_attributesArray objectAtIndex:_attributesArray.count - 1 ];
    CGSize size = CGSizeMake([self collectionView].bounds.size.width, CGRectGetMaxY(lastAttr.frame)+ 10);
    return size;
}

-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat firstH = (SCREEN_HEIGHT - NAVIBAR_HEIGHT - STATUS_HEIGHT) * 2 / 3.0;
    CGFloat width = (SCREEN_WIDTH - GAP * 3) / 2.0;//
    CGFloat height = HYReceivedCellHeight;//
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    if (indexPath.row == 0)
    {
        attributes.frame = CGRectMake(0, 0, SCREEN_WIDTH, firstH);
    }
    else
    {
        CGRect frame = [_attributesArray[0] frame];//获取第一个cell的frame
        
        attributes.frame = CGRectMake((indexPath.row - 1) % 2 * (width + GAP ) + GAP,  (indexPath.row - 1) / 2 * (height + GAP) + GAP + CGRectGetMaxY(frame) , width, height) ;//CGRectMake(left, top, width, height)
    }
    return attributes;
}
@end
